package com.example.demo.config.recode;

import lombok.Data;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Data
public class ReCodeAuthenticationFilter extends
        AbstractAuthenticationProcessingFilter {
    private ReCodeManage reCodeManage;
    private String appid;
    protected ReCodeAuthenticationFilter(String appid) {
        super(new AntPathRequestMatcher("/login/"+appid+"/okcode", "GET"));
        this.appid=appid;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String code = request.getParameter( "code" );
        ReCode reCode = reCodeManage.getCode( code );
        String openid = reCode.getOpenid();
        ReCodeAuthenticationToken authRequest = new ReCodeAuthenticationToken();
        setDetails(request, authRequest);
        authRequest.setPrincipal( reCode.getInfo() );
        authRequest.setCredentials(  reCode.getMpUser());
        return this.getAuthenticationManager().authenticate(authRequest);
    }
    protected void setDetails(HttpServletRequest request,
                              ReCodeAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
